package com.agnes.network.observer;

import com.agnes.network.callback.RespCallback;
import com.orhanobut.logger.Logger;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;

/**
 * Desc:
 * Creator ling
 * Date:   2017/12/18 0018 15:33
 */

public abstract class BaseObserver<D, T> implements Observer<T> {

    protected RespCallback<D> mResponseCallback;
    private CompositeDisposable mCompositeDisposable;

    public BaseObserver(RespCallback<D> responseCallback, CompositeDisposable compositeDisposable) {
        mResponseCallback = responseCallback;
        mCompositeDisposable = compositeDisposable;
    }
    @Override
    public void onSubscribe(@NonNull Disposable d) {
        mCompositeDisposable.add(d);
        mResponseCallback.onStart();
    }

    @Override
    public void onError(@NonNull Throwable e) {
        e.printStackTrace();
        if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            //httpException.response().errorBody().string()
            int code = httpException.code();
            String msg = httpException.getMessage();
            if (code == 504) {
                msg = "网络不给力";
            }
            if (code == 502 || code == 404) {
                msg = "服务器异常，请稍后再试";
            }
            onFailure(msg);
        } else {
            onFailure(e.getMessage());
        }

        mResponseCallback.onFinish();
    }

    @Override
    public void onComplete() {
        mResponseCallback.onFinish();
    }

    protected void onFailure(String msg) {
        Logger.e("BaseObserver==>>"+msg);
        mResponseCallback.onFailure(new RuntimeException(msg));
    }


}
